import {Component} from 'react';
import React from 'react';

import {Button, Collapse, Divider, Form, Input, message, Select, Switch} from 'antd';
import CollapsePanel from 'antd/lib/collapse/CollapsePanel';
import {ProColumns} from '@ant-design/pro-table';
import HighPerformTable from '@/components/HighPerformTable';
import {PlusOutlined} from '@ant-design/icons';
import ImageUpload from '@/components/ImageUpload';
import APIS from '@/apis';
import {FormInstance} from 'antd/lib/form';

class WebSite extends Component<any, any> {
  linkActionRef: any;
  bannerActionRef: any;
  fromRef: FormInstance | null;

  state = {
    linkRecords: [],
    bannerRecords: [],
    selectBanner: null,
    selectFreind: null,
    edit: false
  }

  async componentDidMount() {
    var res = await APIS.UtilsAPI.GetConfig();
    if (res.code = 10000) {
      try {
        var config = JSON.parse(res.data);
        this.fromRef?.setFieldsValue(config);
        this.setState(config);
        console.log(config)
        this.setState({
          linkRecords: config.linkRecords ? config.linkRecords : [],
          bannerRecords: config.bannerRecords ? config.bannerRecords : [],
        })
        return
      } catch (error) {

      }

    }
    this.fromRef?.setFieldsValue({
      article: false,
      copyright: "",
      living: false,
      interactive: false,
      mode: "",
      qq: "",
      school: "",
      siteIcon: "",
      siteLogo: "",
      siteName: "",
      tel: "",
      vr: false
    })
  }

  requestGetLinkData(
    params: {
      pageSize?: number;
      current?: number;
    },
    sorter: {
      [key: string]: 'ascend' | 'descend';
    },
    filter: {
      [key: string]: React.ReactText[];
    },
  ) {
    const result = {
      data: this.state.linkRecords,
      total: this.state.linkRecords.length,
      success: true,
      pageSize: params.pageSize,
      current: parseInt(`${params.current}`, 10) || 1,
    };
    return Promise.resolve(result);
  }

  requestGetBannerData(
    params: {
      pageSize?: number;
      current?: number;
    },
    sorter: {
      [key: string]: 'ascend' | 'descend';
    },
    filter: {
      [key: string]: React.ReactText[];
    },
  ) {
    const result = {
      data: this.state.bannerRecords,
      total: this.state.bannerRecords.length,
      success: true,
      pageSize: params.pageSize,
      current: parseInt(`${params.current}`, 10) || 1,
    };
    // console.log(result);
    return Promise.resolve(result);
  }

  AddBanner(data: any) {
    if (this.state.selectBanner) {
      data = Object.assign({}, data, this.state.selectBanner);
    }
    var datas: Array<any> = [...this.state.bannerRecords];
    if (datas.length >= 5) {
      message.error("无法添加更多数据")
      return Promise.resolve(false)
    }
    if (datas.find((item) => data.title === item.title) >= 0) {
      message.error("已存在同名数据")
      return Promise.resolve(false)
    }
    //APIS.Website.CreateNewBanner(data);
    datas.push({...data, state: 1});
    // console.log(datas);
    this.setState({bannerRecords: datas});
    return Promise.resolve(true)
  }

  DeleteBanner(data: any) {
    var datas: Array<any> = [...this.state.bannerRecords];
    var index = datas.findIndex((item) => data.name == item.name);
    if (index >= 0) {
      datas.splice(index, 1);
    }
    this.setState({bannerRecords: datas});
    //this.forceUpdate();
    return Promise.resolve(true)
  }

  UpdateBanner(data: any) {
    console.log(data);
    const {selectBanner} = this.state;
    let temp = [...this.state.bannerRecords];
    // @ts-ignore
    temp.forEach((element: any, index) => {
      if (element.name === selectBanner.name) {
        data.image = selectBanner.image;
        // @ts-ignore
        temp[index] = data;
      }
    });
    this.setState({bannerRecords: temp});
    this.bannerActionRef?.reload();
    return Promise.resolve(true)
  }

  UpdateFriend(data: any) {
    console.log(data);
    const {selectFreind} = this.state;
    let temp = [...this.state.linkRecords];
    // @ts-ignore
    temp.forEach((element: any, index) => {
      if (element.name === selectFreind.name) {
        // @ts-ignore
        temp[index] = data;
      }
    });
    this.setState({linkRecords: temp});
    this.linkActionRef?.reload();
    return Promise.resolve(true)
  }

  AddFriendLink(data: any) {
    var datas: Array<any> = [...this.state.linkRecords];
    if (datas.length >= 8) {
      message.error("无法添加更多数据")
      return Promise.resolve(false)
    }
    if (datas.find((item) => data.title === item.title) >= 0) {
      message.error("已存在同名数据")
      return Promise.resolve(false)
    }
    datas.push({...data, state: 1});
    this.setState({linkRecords: datas});
    return Promise.resolve(true)
  }

  DeleteFriendLink(data: any) {
    var datas: Array<any> = [...this.state.linkRecords];
    var index = datas.findIndex((item) => data.name == item.name);
    if (index >= 0) {
      datas.splice(index, 1);
    }
    this.setState({linkRecords: datas});
    return Promise.resolve(true)
  }

  submitSiteConfig() {
    this.fromRef?.validateFields().then((data: any) => {
      const {linkRecords, bannerRecords, selectBanner, selectFreind} = this.state;
      const site = {
        linkRecords: linkRecords,
        bannerRecords: bannerRecords,
        selectFreind: selectFreind,
        selectBanner: selectBanner
      };
      const msg = Object.assign({}, data, site);
      APIS.UtilsAPI.SaveConfig(JSON.stringify(msg)).then((resp) => {
        if (resp.code === 10000)
          message.success("编辑成功")
      });
    })
  }

  render() {

    const FormItem = Form.Item;
    const layout = {
      labelCol: {span: 4},
      wrapperCol: {span: 12},
    };
    /*const tailLayout = {
      wrapperCol: { offset: 8, span: 16 },
    };*/
    const linkColumns: ProColumns<any>[] = [
      {
        title: '标题',
        dataIndex: 'name',
        filters: true,
        // @ts-ignore
        onFilter: true,
        valueType: 'text'
      },
      {
        title: '链接',
        dataIndex: 'url',
        filters: true,
        valueType: "text"
      }
    ]

    const bannerColumns: ProColumns<any>[] = [
      {
        title: '标题',
        dataIndex: 'name',
        filters: true,
        // @ts-ignore
        onFilter: true,
        colSize: 1,
        valueType: 'text',
        renderFormItem: (item: any, config: any, form: FormInstance) => {
          return <Input disabled={this.state.edit}/>
        }
      },
      {
        title: '链接',
        dataIndex: 'url',
        filters: true,
        valueType: "text",
      },
      {
        title: '图片',
        dataIndex: 'image',
        filters: true,
        valueType: "text",
        renderFormItem: (item: any, config: any, form: FormInstance) => {
          const {selectBanner} = this.state;
          return <ImageUpload
            preImage={selectBanner?.image}
            handleImageChange={(url: any) => {
              let temp = selectBanner ? selectBanner : {image: ""};
              temp.image = url;
              this.setState({selectBanner: temp});
            }}
          />
        }
      }
    ]
    return (
      <Form ref={ref => this.fromRef = ref} {...layout} onFinish={this.submitSiteConfig.bind(this)}>
        <Collapse accordion defaultActiveKey="basic">
          <CollapsePanel key="basic" header="基础信息">
            <FormItem required name="siteName" label="站点名称">
              <Input></Input>
            </FormItem>
            <FormItem required name="school" label="部署单位名称">
              <Input></Input>
            </FormItem>
            <FormItem required name="siteIcon" label="站点Icon">
              <ImageUpload
                preImage={this.fromRef?.getFieldValue("siteIcon")}
                handleImageChange={(url: any) => {
                  this.fromRef?.setFieldsValue({siteIcon: url});
                  this.forceUpdate()
                }}
              ></ImageUpload>
            </FormItem>
            <FormItem required name="siteLogo" label="站点Logo">
              <ImageUpload
                preImage={this.fromRef?.getFieldValue("siteLogo")}
                handleImageChange={(url: any) => {
                  this.fromRef?.setFieldsValue({siteLogo: url});
                  this.forceUpdate()
                }}
              ></ImageUpload>
            </FormItem>
            <FormItem required name="tel" label="联系电话">
              <Input></Input>
            </FormItem>
            <FormItem required name="qq" label="联系QQ">
              <Input></Input>
            </FormItem>
            <FormItem required name="copyright" label="版权信息">
              <Input></Input>
            </FormItem>
            <FormItem required name="mode" label="首页展示类型">
              <Select>
                <Select.Option title="学校" value={1}>学校</Select.Option>
                <Select.Option title="公司" value={2}>公司</Select.Option>
              </Select>
            </FormItem>
            <FormItem required name="vr" label="虚拟仿真实验课程">
              <Switch checked={this.fromRef?.getFieldValue("vr")} onChange={(v) => {
                this.fromRef.setFieldsValue({vr: v});
                this.forceUpdate()
              }}></Switch>
            </FormItem>
            <FormItem required name="interactive" label="互动体验课程">
              <Switch checked={this.fromRef?.getFieldValue("interactive")} onChange={(v) => {
                this.fromRef.setFieldsValue({interactive: v});
                this.forceUpdate()
              }}></Switch>
            </FormItem>
            <FormItem required name="article" label="文章分享课程">
              <Switch checked={this.fromRef?.getFieldValue("article")} onChange={(v) => {
                this.fromRef.setFieldsValue({article: v});
                this.forceUpdate()
              }}></Switch>
            </FormItem>
            <FormItem required name="living" label="直播课程">
              <Switch checked={this.fromRef?.getFieldValue("living")} onChange={(v) => {
                this.fromRef.setFieldsValue({living: v});
                this.forceUpdate()
              }}></Switch>
            </FormItem>
          </CollapsePanel>
          <CollapsePanel key="banner" header="顶部banner">
            <HighPerformTable<any>
              columns={bannerColumns}
              // @ts-ignore
              rowKey={record => record.name}
              requestGetData={this.requestGetBannerData.bind(this)}
              ref={(ref: any) => (this.bannerActionRef = ref)}
              onClickUpdate={record => {
                this.bannerActionRef.handleUpdateModalVisible(true, record);
                let obj = Object.assign({}, record);
                this.setState({selectBanner: obj, edit: true});
              }}
              handleUpdate={(item) => this.UpdateBanner(item)}
              handleDelete={(id) => this.DeleteBanner(id)}
              hidePagination
              toolBarRender={() => [
                <Button type="primary" onClick={() => {
                  this.bannerActionRef.handleModalVisible(true)
                  this.setState({selectBanner: null, edit: false});
                }}>
                  <PlusOutlined/> 新增Banner
                </Button>,
              ]}
              handleAdd={this.AddBanner.bind(this)}
            />
          </CollapsePanel>
          <CollapsePanel key="2" header="友情链接">
            <HighPerformTable<any>
              columns={linkColumns}
              requestGetData={this.requestGetLinkData.bind(this)}
              hidePagination
              ref={(ref: any) => (this.linkActionRef = ref)}
              onClickUpdate={record => {
                this.linkActionRef.handleUpdateModalVisible(true, record);
                let obj = Object.assign({}, record);
                this.setState({selectFreind: obj});
              }}
              handleDelete={this.DeleteFriendLink.bind(this)}
              toolBarRender={() => [
                <Button type="primary" onClick={() => this.linkActionRef.handleModalVisible(true)}>
                  <PlusOutlined/> 新增友情链接
                </Button>,
              ]}
              handleUpdate={(item) => this.UpdateFriend(item)}
              handleAdd={this.AddFriendLink.bind(this)}
            />
          </CollapsePanel>
        </Collapse>
        <Divider></Divider>
        <Button type="ghost" htmlType="submit">提交</Button>
      </Form>
    );
  }
}

export default WebSite;
